package com.cardbaobao.cardbabyclient.ui.activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.AgreementWebViewActivity;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.controller.BroadcastController;
import com.cardbaobao.cardbabyclient.model.UserInfo;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.LoansUtils;
import com.cardbaobao.cardbabyclient.utils.PhoneInfoUtil;
import com.cardbaobao.cardbabyclient.utils.RegularUtil;
import com.cardbaobao.cardbabyclient.utils.SpanUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.utils.UmengEventUtils;
import com.cardbaobao.cardbabyclient.widget.TitleBar;
import com.gyf.barlibrary.ImmersionBar;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import rx.Observable;
import rx.Subscriber;

/**
 * Description:
 * Created by FHW
 * on 2017/6/16
 */
public class RegisterActivity extends BaseActivity {
    @BindView(R.id.tw_toolbar)
    TitleBar tw_toolbar;

    @BindView(R.id.edtext_phone)
    EditText mPhoneEd;//手机号输入框
    @BindView(R.id.msg_code)
    EditText mMsgCodeEd;//验证码输入框
    @BindView(R.id.edtext_pass)
    EditText mPassEd;//密码输入框

    @BindView(R.id.send_msg_code)
    TextView mSendMsgCode;//发送验证码
    @BindView(R.id.register_xiyi_icon)
    ImageView register_xiyi_icon;//确定协议

    @BindView(R.id.register_xiyi)
    TextView register_xiyi;//协议
    @BindView(R.id.bt_register)
    Button btRegister;//提交注册

    private String msgCode = "";
    /**
     * 是否同意协议
     */
    private boolean isAssentXiyi = true;

    private String mPhone = "";

    private RegisterActivity.MyCountDownTimer timer;

    private String plat_from_type = "";//从哪个页面进到注册页面的(从哪个页面进到登录页然后到注册页)


    @Override
    protected void initView(Bundle savedInstanceState) {
        ImmersionBar.with(this).statusBarDarkFont(true, Constant.STATUS_BAR_FONT_ALPHA).keyboardEnable(true).init();
        initIntent();
        initRegisterTermEvent();
        tw_toolbar.setRightViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mCurrentPageId = Self.Page.app_register_page;

        plat_from_type = getIntent().getStringExtra(AccountLoginActivity.LOGIN_REQUEST_FROM_S);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mPhone = getIntent().getStringExtra("phone");
        if (!TextUtils.isEmpty(mPhone) && RegularUtil.isPhoneNumber(mPhone)) {
            mPhoneEd.setText(mPhone);
            checkPhone();
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_register_new;
    }

    @Override
    protected void onResume() {
        super.onResume();
        UmengEventUtils.pageEvent(mContext,
                ApplicationHelper.getApplicationContext().getString(R.string.event_0x030));
        GoogleAnalyticsUtil.setScreenName(Google.REGISTER);
    }

    /**
     * 检测手机号是否注册过
     */
    private void checkPhone() {
        final String phone = mPhoneEd.getText().toString().trim();
        if (RegularUtil.isPhoneNumber(phone)) {
            showProgressDialog(false, "发送中...");
            Observable<String> observable = Api.checkPhoneRegistered(phone);
            observable.subscribe(new Subscriber<String>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    dismissProgressDialog();
                    ToastUtil.showToast(ApplicationHelper.
                            getApplicationContext().
                            getString(R.string.string_request_server_fail));
                }

                @Override
                public void onNext(String s) {
                    dismissProgressDialog();
                    JSONObject object = JSON.parseObject(s);
                    if (object.getIntValue("code") == 1) {
                        ToastUtil.showToast("该手机号已经注册");
                    } else {
                        sendMsgCode(phone);
                    }
                }
            });
        } else {
            ToastUtil.showToast("请输入正确的手机号码");
        }
    }

    /**
     * 发送验证码
     *
     * @param phone
     */
    private void sendMsgCode(final String phone) {
        msgCode = String.valueOf(LoansUtils.getMsgCode());
        Observable<String> observable =
                Api.sendSms(phone, Constant.VERIFY_CODE_TYPE, msgCode, Constant.GDX030101);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                msgCode = "";
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                JSONObject object = JSON.parseObject(s);
                if (object.getIntValue("status") == 1) {
                    if (timer != null) {
                        timer.cancel();
                        timer = null;
                    }
                    timer = new RegisterActivity.MyCountDownTimer(90l * 1000l, 1000L);
                    timer.start();
                    mSendMsgCode.setEnabled(false);
                    mSendMsgCode.setText("90s后重发");
                    mSendMsgCode.setTextColor(ContextCompat.getColor(mContext, R.color.color_666666));
                    ToastUtil.showToast("验证码发送成功");
                    mPhone = phone;
                } else {
                    ToastUtil.showToast(object.getString("result"));
                    msgCode = "";
                }
            }
        });
    }

    @OnClick({R.id.register_xiyi_icon, R.id.send_msg_code, R.id.bt_register, R.id.tv_login})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.register_xiyi_icon:
                //同意协议
                if (isAssentXiyi) {
                    register_xiyi_icon.setImageResource(R.mipmap.icon_register_normal);
                    isAssentXiyi = false;
                } else {
                    register_xiyi_icon.setImageResource(R.mipmap.icon_register_check);
                    isAssentXiyi = true;
                }
                break;
            case R.id.send_msg_code:
                //发送验证码
                checkPhone();
                break;
            case R.id.bt_register:
                //提交注册
                registerCommit();
                break;
            case R.id.tv_login:
                mIntent.setClass(mContext, AccountLoginActivity.class);
                mIntent.putExtra("type", 1);
                startActivity(mIntent);
                break;
        }
    }

    /**
     * 提交注册
     */
    public void registerCommit() {
        String phone = mPhoneEd.getText().toString().trim();
        String msg = "";
        if (!phone.isEmpty() && RegularUtil.isPhoneNumber(phone)) {
            String msgCodes = mMsgCodeEd.getText().toString().trim();
            if (TextUtils.isEmpty(msgCodes)) {
                msg = "请输入验证码";
            } else {
                if (!msgCodes.equals(msgCode)) {
                    msg = "验证码错误";
                }
            }
            if (!TextUtils.isEmpty(msg)) {
                ToastUtil.showToast(msg);
                return;
            }
            //注册号码需与接收验证码的手机号码一致
            if (!phone.equals(mPhone)) {
                ToastUtil.showToast("非法操作");
                return;
            }
            String password = mPassEd.getText().toString().trim();
            if (!password.isEmpty() && password.length() >= 6) {
                if (isAssentXiyi) {
                    registerUserData(phone, password);
                } else {
                    msg = "请同意卡宝宝申请协议";
                }
            } else if (TextUtils.isEmpty(password)) {
                msg = "请输入密码";
            } else {
                msg = "密码最少为6位";
            }
        } else {
            msg = "请输入正确的手机号";
        }
        if (!msg.isEmpty()) {
            ToastUtil.showToast(msg);
        }
    }

    /**
     * 提交注册数据
     *
     * @param phone
     * @param pass
     */
    private void registerUserData(final String phone, String pass) {
        showChangeTextView("正在注册");
        //将渠道与code对应起来
        String channelCode;
        switch (PhoneInfoUtil.getApkChannelName(mContext)) {
            case "cbb":
                channelCode = "CLY0101";
                break;
            case "pc":
                channelCode = "CLY0102";
                break;
            case "m":
                channelCode = "CLY0103";
                break;
            case "wx":
                channelCode = "CLY0104";
                break;
            case "duanxin":
                channelCode = "CLY0105";
                break;
            case "yingyongbao":
                channelCode = "CLY0106";
                break;
            case "oppo":
                channelCode = "CLY0107";
                break;
            case "vivo":
                channelCode = "CLY0108";
                break;
            case "aliyun":
                channelCode = "CLY0109";
                break;
            case "xiaomi":
                channelCode = "CLY0110";
                break;
            case "zhushou360":
                channelCode = "CLY0111";
                break;
            case "huawei":
                channelCode = "CLY0112";
                break;
            case "sanxing":
                channelCode = "CLY0113";
                break;
            case "yingyonghui":
                channelCode = "CLY0114";
                break;
            case "anzhi":
                channelCode = "CLY0115";
                break;
            case "android":
                channelCode = "CLY0116";
                break;
            case "zhushou91":
                channelCode = "CLY0117";
                break;
            case "meizu":
                channelCode = "CLY0118";
                break;
            case "mumayi":
                channelCode = "CLY0119";
                break;
            case "jifeng":
                channelCode = "CLY0120";
                break;
            case "hao123":
                channelCode = "CLY0121";
                break;
            case "jinli":
                channelCode = "CLY0122";
                break;
            case "lenovo":
                channelCode = "CLY0123";
                break;
            case "liqu":
                channelCode = "CLY0124";
                break;
            case "nduo":
                channelCode = "CLY0125";
                break;
            case "feifanruanjian":
                channelCode = "CLY0126";
                break;
            case "tianyi":
                channelCode = "CLY0127";
                break;
            case "liantongwo":
                channelCode = "CLY0128";
                break;
            case "zhongyidong":
                channelCode = "CLY0129";
                break;
            case "yamaxun":
                channelCode = "CLY0130";
                break;
            case "youyi":
                channelCode = "CLY0131";
                break;
            case "uc":
                channelCode = "CLY0132";
                break;
            case "taipingyang":
                channelCode = "CLY0133";
                break;
            case "ppzhushou":
                channelCode = "CLY0134";
                break;
            case "pc6":
                channelCode = "CLY0135";
                break;
            case "yiyou":
                channelCode = "CLY0136";
                break;
            case "qitu":
                channelCode = "CLY0137";
                break;
            case "jufeng":
                channelCode = "CLY0138";
                break;
            case "sougouzhushou":
                channelCode = "CLY0139";
                break;
            case "chuizi":
                channelCode = "CLY0140";
                break;
            case "leshi":
                channelCode = "CLY0141";
                break;
            case "aiqiyi":
                channelCode = "CLY0142";
                break;
            case "maopaotang":
                channelCode = "CLY0143";
                break;
            case "appfun":
                channelCode = "CLY0144";
                break;
            case "anzhuoyuan":
                channelCode = "CLY0145";
                break;
            default:
                channelCode = "CLY0101";
        }
        Observable<String> observable = Api.register(phone, pass, plat_from_type, channelCode);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                hideChangeTextView();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                hideChangeTextView();
                JSONObject object = JSON.parseObject(s);
                if (object.getIntValue("code") == 1) {
                    UserInfo user = JSON.parseObject(object.getJSONObject("msg").getString("data"), UserInfo.class);
                    user.setPhone(phone);
                    mApplication.setUser(user);
                    ToastUtil.showToast("注册成功");
                    setResult(Activity.RESULT_OK);
                    mIntent.setClass(RegisterActivity.this, MainActivity.class);
                    startActivity(mIntent);
                    finish();
                    new BroadcastController(mApplicationContext).notifyUserLogin();
                } else {
                    ToastUtil.showToast(object.getString("msg"));
                }
            }
        });
    }


    @OnTextChanged({R.id.edtext_phone, R.id.msg_code, R.id.edtext_pass})
    public void afterTextChange(Editable s) {
        if (mPhoneEd.getText().length() > 0 &&
                mPassEd.getText().length() > 0 &&
                mMsgCodeEd.getText().length() > 0) {
            btRegister.setEnabled(true);
        } else {
            btRegister.setEnabled(false);
        }
    }

    public void showChangeTextView(String showText) {
        super.showProgressDialog(false, showText);
        btRegister.setEnabled(false);
        mPhoneEd.setEnabled(false);
        mMsgCodeEd.setEnabled(false);
        mSendMsgCode.setEnabled(false);
        mPassEd.setEnabled(false);
    }

    public void hideChangeTextView() {
        super.dismissProgressDialog();
        btRegister.setEnabled(true);
        mPhoneEd.setEnabled(true);
        mMsgCodeEd.setEnabled(true);
        mSendMsgCode.setEnabled(true);
        mPassEd.setEnabled(true);
    }

    //定时器
    class MyCountDownTimer extends CountDownTimer {
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mSendMsgCode.setText(millisUntilFinished / 1000 + "s后重发");
        }

        @Override
        public void onFinish() {
            mSendMsgCode.setText("重新发送");
            mSendMsgCode.setEnabled(true);
            timer = null;
        }
    }

    /**
     * 初始化注册条款单击事件
     */
    private void initRegisterTermEvent() {
        SpanUtil.setTextHyperLink(register_xiyi,
                register_xiyi.getText().toString(),
                "《卡宝宝注册条款》",
                ContextCompat.getColor(mContext, R.color.color_222222), false, new SpanUtil
                        .SpanClickListener() {
                    @Override
                    public void onSpanClick(View v) {
                        //卡宝宝的申请条款文字单击事件
                        mIntent.setClass(mContext, AgreementWebViewActivity.class);
                        mIntent.putExtra("title", "卡宝宝注册条款");
                        mIntent.putExtra("webUrl", URLUtil.REGISTRATION_AGREEMENT);
                        mIntent.putExtra(AgreementWebViewActivity.WEB_TYPE_I, 8);
                        mIntent.putExtra(PRE_PAGE_ID_S, mCurrentPageId);
                        UmengEventUtils.pageEvent(mContext,
                                ApplicationHelper.getApplicationContext().getString(R.string.event_0x031));
                        mContext.startActivity(mIntent);
                    }
                });
    }

}
